<?php
/**
 *                    _ooOoo_
 *                   o8888888o
 *                   88" . "88
 *                   (| -_- |)
 *                    O\ = /O
 *                ____/`---'\____
 *              .   ' \\| |// `.
 *               / \\||| : |||// \
 *             / _||||| -:- |||||- \
 *               | | \\\ - /// | |
 *             | \_| ''\---/'' | |
 *              \ .-\__ `-` ___/-. /
 *           ___`. .' /--.--\ `. . __
 *        ."" '< `.___\_<|>_/___.' >'"".
 *       | | : `- \`.;`\ _ /`;.`/ - ` : | |
 *         \ \ `-. \_ __\ /__ _/ .-` / /
 * ======`-.____`-.___\_____/___.-`____.-'======
 *                    `=---='
 *
 * .............................................
 *          佛祖保佑             永无BUG
 */

namespace App\Repositories;


use App\Coupon;
use App\CouponSetting;
use App\Interfaces\CouponService;
use App\Notifications\WechatNotification;
use App\User;
use App\UserCoupon;
use Carbon\Carbon;

class CouponRepository implements CouponService
{
    public function sendCoupon(User $user,$type=0)
    {
        if($type==0){
            //查询符合条件的优惠券
           $couponSetting= CouponSetting::where('type',0)->where('start_time','<',Carbon::now())->where('end_time','>',Carbon::now())->get();
        }elseif ($type==1){
            //todo 条件优惠券

        }
        //写入用户coupon表
        $data=[];
        foreach ($couponSetting as $v){
            $data[]=[
                'user_id'=>$user->id,
                'conpon_id'=>$v->coupon_id,
                'staus'=>0,
                'created_at'=>Carbon::now()
                ];
           /* //通知
            $coupon= Coupon::find($v->coupon_id);
            if($coupon){
                $user->notify(new WechatNotification('您获得了'.$coupon->name.'请查收'));
            }*/
        }
        \DB::table('user_coupons')->insert($data);
    }
    public function sendOne(User $user,$coupon_id){
        $userCoupon=new UserCoupon();
        $userCoupon->user_id=$user->id;
        $userCoupon->staus=0;
        $userCoupon->conpon_id=$coupon_id;
        $userCoupon->save();
       /* $coupon= Coupon::find($coupon_id);
        if($coupon){
            $user->notify(new WechatNotification('您获得了'.$coupon->name.'请查收'));
        }*/

    }
    public function getUserCoupon($user_id,$search='')
    {

        $user= UserCoupon::join('coupons','user_coupons.conpon_id','=','coupons.id')->where('user_coupons.user_id',$user_id);
        if(isset($search['type_status'])&&$search['type_status']==1){//未使用
            $user=$user->where('user_coupons.staus',0)->where('coupons.end_time','>',Carbon::now());
        }elseif (isset($search['type_status'])&&$search['type_status']==2){//已使用
            $user=$user->where('user_coupons.staus',1);
        }elseif (isset($search['type_status'])&&$search['type_status']==3){//已失效
            $user=$user->where('coupons.end_time','<',Carbon::now());
        }

       return $user=$user->get();
       // dd($user);
    }
}